package com.Guo.auth;

import com.Guo.jwt.JwtTokenUtil;
import com.Guo.response.Result;
import com.Guo.system.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Admin
 * @project MyAuthenticationSuccessHandler
 * @description
 * @date 2020-12-15-15:14
 */
@Component("authenticationSuccessHandler")
public class MyAuthenticationSuccessHandler extends JSONAuthentication implements AuthenticationSuccessHandler {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //将登录成功的授权信息置于springsecurity中
        SecurityContextHolder.getContext().setAuthentication(authentication);
        //更新用户表上次登录时间、更新人、更新时间等字段
        User userDetails = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        com.Guo.system.entity.User user = userMapper.selectByName(userDetails.getUsername());
        userMapper.updateById(user);
        //生成token
        String token = jwtTokenUtil.generateToken(userDetails);
        Result message = Result.ok().message("登录成功").data("token",token);
        this.WriteJSON(response,request,message);
    }
}
